import { useUserStore } from '@/store/modules/user'


let isReloginPrompting = false

export function getReloginStatus(): boolean {
  return isReloginPrompting
}

export function setReloginStatus(value: boolean): void {
  isReloginPrompting = value
}

export async function showReloginModal(): Promise<void> {
  return new Promise((resolve) => {
    // 获取当前页面路径和参数
    const pages = getCurrentPages()
    const currentPage: any = pages[pages.length - 1]
    console.log('currentPage', currentPage);

    const route = `/${currentPage.route}`
    const query = currentPage.options
    const queryString = Object.entries(query || {})
      .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
      .join('&')
    const currentFullPath = queryString ? `${route}?${queryString}` : route
    console.log('currentFullPath', currentFullPath);
    console.log('encodeURIComponent(currentFullPath)', encodeURIComponent(currentFullPath));

    uni.showModal({
      title: '提示',
      content: '登录状态已过期，请重新登录',
      showCancel: false,
      confirmText: '确定',
      success() {
        setReloginStatus(false)
        const userStore = useUserStore()
        userStore.logout()
        // 跳转登录页，并传 redirect 参数
        uni.reLaunch({ url: `/pages/login/index?redirect=${encodeURIComponent(currentFullPath)}` })
        resolve()
      },
      fail() {
        setReloginStatus(false)
        resolve()
      },
    })
  })
}

const ACCESS_TOKEN_KEY = 'ACCESS_TOKEN_KEY'
const REFRESH_TOKEN_KEY = 'REFRESH_TOKEN_KEY'
const EXPIRES_TIME_KEY = 'EXPIRES_TIME_KEY'

// ========== Token 相关 ==========

export function getAccessToken() {
  return uni.getStorageSync(ACCESS_TOKEN_KEY)
}

export function getRefreshToken() {
  return uni.getStorageSync(REFRESH_TOKEN_KEY)
}

export function getExpiresTime() {
  return uni.getStorageSync(EXPIRES_TIME_KEY)
}

export function setToken({ accessToken, refreshToken, expiresTime }: any) {
  uni.setStorageSync(ACCESS_TOKEN_KEY, accessToken)
  uni.setStorageSync(REFRESH_TOKEN_KEY, refreshToken)
  uni.setStorageSync(EXPIRES_TIME_KEY, expiresTime) // 时间戳毫秒
}

export function removeToken() {
  uni.removeStorageSync(ACCESS_TOKEN_KEY)
  uni.removeStorageSync(REFRESH_TOKEN_KEY)
  uni.removeStorageSync(EXPIRES_TIME_KEY)
}
